//
//  ComposeViewController.swift
//  Weibo
//
//  Created by apple on 15/12/22.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    
    //自定义表情键盘视图
    private lazy var emoticonKeyboardView: EmoticonKeyboardView = EmoticonKeyboardView { [weak self](em) -> () in
        //点击的事件就可以回调到这个地方
        //        print(em)
        self?.textView.insertEmoticon(em)
    }
    
    //响应方法 写在视图控制器的最上面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK:选择图片
    @objc private func selectPicture() {
        print(__FUNCTION__)
        //1.隐藏键盘
        textView.resignFirstResponder()
        //2.更新图片选择器的高度
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH / 3 * 2)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            //闭包的内部 执行强制刷新
            self.view.layoutIfNeeded()
        }
        
    }
    
    // MARK:选择表情键盘
    @objc private func selectEmoticonKeyboard() {
        print(__FUNCTION__)
        //使用自定义键盘   指定 inputView
        //先让键盘失去第一响应者\ 系统键盘存在的时候  inputView = nil;
        
        print(textView.inputView)
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonKeyboardView : nil
        textView.becomeFirstResponder()
    }
    
    // MARK:发布微博
    @objc private func send() {
        print(__FUNCTION__)
        
        var urlString = "2/statuses/update.json"
        
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showInfoWithStatus("请重新登录", maskType: .Gradient)
            return
        }
        
        let parameter = ["access_token": token,"status": textView.fullText() ?? ""]
        
        if pictureSelectorVC.imageList.count != 0 {
            //上传图片
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //调用上传图片的接口
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)
            NetworkTools.sharedTools.uploadImage(urlString, parameters: parameter, imageData: imageData!, finished: { (dict, error) -> () in
                self.finishedUpdateStatus(dict, error: error)
            })
        } else {
            //发布文本微博
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameter) { (dict, error) -> () in
                self.finishedUpdateStatus(dict, error: error)
            }
        }
        
    }
    
    //微博发布完后的页面交互
    private func finishedUpdateStatus(dict: [String : AnyObject]?, error: NSError?) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("发布微博失败,请检查网络", maskType: .Gradient)
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: .Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureSelectorVC.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
        
    }
    
    //懒加载子视图
    private lazy var textView: EmoticonTextView = {
        let tv = EmoticonTextView()
        
//        tv.text = "输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var pictureSelectorVC: PictureSelectorViewController = PictureSelectorViewController()
    
    //析构函数
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension ComposeViewController: UITextViewDelegate {
    //要实时监测文本的改变 
    func textViewDidChange(textView: UITextView) {
        //根据 textView是否有文本 隐藏占位文本  开启发送按钮的交互
        placeHolderLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeViewController {
    //设置UI
    private func setupUI() {
        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        setNavbBar()
        //在导航控制器 + ScrollView 在自动布局中需要注意的事项   推荐自上而下添加约束
        //就应该要注意
        //1.如果首先添加的约束 是从顶部开始添加约束 这个时候会自动开启 topLayouGuide scrollView对应的contentInset.top = 64
        // 2.如果首先添加的约束 是从底部开始 这个时候会自动开启 bottomLayouGuide scrollView对应的contentInset.bottom = 44
        setTextView()
        
        setToolBar()
        
        setPictureSeletorVC()
        
        //注册通知
        registerNotification()
    }
    
    private func setPictureSeletorVC() {
        //首先添加视图控制器
        addChildViewController(pictureSelectorVC)
        //添加视图控制器的根视图
        view.addSubview(pictureSelectorVC.view)
        //将 toolBar 移动到视图的最顶层
        view.bringSubviewToFront(toolBar)
        //设置约束和布局
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    @objc private func keyboardWillChange(n: NSNotification) {
        print(n)
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //动画曲线值 为了抵消动画时间  对视图动画的影响
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        print(duration,endRect)
        let offsetY = -screenH + endRect.origin.y
        //移动toolBar位置 
        //需要改变toolBar的约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新的方法 必须放到动画闭包中执行 才会有动画效果
            //在动画闭包中设置动画的曲线值 一旦设置了曲线值 动画时间 就失效
            //需要通过原始值 来实例化枚举对象
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func setToolBar() {
        //给toolBar 设置  items 数组 
        var items = [UIBarButtonItem]()
        //向数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        //遍历配置的数组
        for item in itemSettings {
            let imageName = item["imageName"]
            let itemBtn = UIButton(imageName: nil, backImageName: imageName!)
            if let action = item["actionName"] {
                // addTarget 可以将字符串 直接转换为 Selector类型 但是 如果传递的是参数 就无法自动包装
                itemBtn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            
            let barButtonItem = UIBarButtonItem(customView: itemBtn)
            //添加到数组中
            items.append(barButtonItem)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
        
        //添加到父视图
        view.addSubview(toolBar)
        // 设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
//            make.height.equalTo(44)
        }
    }
    
    private func setTextView() {
        //添加textView
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(screenH / 3)
        }
        
        //给textView添加文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    // 1. 设置导航条
    private func setNavbBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        //默认发送按钮不允许交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        //自定义titileView
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        
        //添加label
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}
